using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Common
{
    public static class WeiXinHelper
    {

        /// <summary>
        /// 生成签名
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="model">数据</param>
        /// <param name="apikey">apikey</param>
        /// <returns></returns>
        public static string MakeSign<T>(object model, string apikey) where T : class
        {
            T t = model as T;
            //排序
            SortedDictionary<string, object> m_values = new SortedDictionary<string, object>();
            foreach (PropertyInfo p in t.GetType().GetProperties())
            {
                var val = p.GetValue(t);
                if (val == null)
                {
                    continue;
                }
                m_values.Add(p.Name, val);
            }
            //转url格式
            string url_buff = "";
            foreach (KeyValuePair<string, object> pair in m_values)
            {
                if (pair.Value == null)
                {
                    LogHelper.Error("WeiXinHelper生成签名", "生成签名时:内部含有值为null的字段!");
                    throw new Exception("生成签名时:内部含有值为null的字段!");
                }

                if (pair.Key != "sign" && pair.Value.ToString() != "")
                {
                    url_buff += pair.Key + "=" + pair.Value + "&";
                }
            }
            url_buff = url_buff.Trim('&');

            //在string后加入API KEY
            url_buff += "&key=" + apikey;
            //MD5加密
            var md5 = System.Security.Cryptography.MD5.Create();
            var bs = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(url_buff));
            var sb = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                sb.Append(b.ToString("x2"));
            }
            //所有字符转为大写
            return sb.ToString().ToUpper();
        }

    }
}
